package com.njlime.core.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @ClassName:     FileUpload.java
 * @Description:   文件上传
 * 
 * @author         xubin
 * @version        V1.0  
 * @Date           2016-4-20 下午11:13:23 
 */
public class FileUpload {

	public static final String FILE_PATH = "upload\\";
	public static final String FILE_UPLOAD = "upload";

	//文件上传  
    public static String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename(); 
        String path =   request.getSession().getServletContext().getRealPath("/").replace("ss", "");
        File tempFile = new File(path + FILE_PATH, new Date().getTime() + "-" + String.valueOf(fileName));  
        if (!tempFile.getParentFile().exists()) {  
            tempFile.getParentFile().mkdir();  
        }  
        if (!tempFile.exists()) {  
            tempFile.createNewFile();  
        }  
        file.transferTo(tempFile);  
        return path + FILE_PATH + tempFile.getName();  
    }

    //文件上传
    public static String fileUp(MultipartFile file, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileNameNew = DateUtil.timeStr() + fileName.substring(fileName.lastIndexOf("."),fileName.length());
        String path =   request.getSession().getServletContext().getRealPath("/").replace("ss", "");
        File tempFile = new File(path + FILE_UPLOAD + File.separator + filePath(),  String.valueOf(fileNameNew));
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        return  (FILE_UPLOAD + File.separator + filePath()+File.separator + String.valueOf(fileNameNew)).replace(File.separator,"/");
    }

    public static String filePath (){
        Date now = new Date();
        return DateUtil.dateFormat(now, "yyyyMM") + File.separator + DateUtil.dateFormat(now, "hhmm");
    }
  
    public static File getFile(String fileName) {  
        return new File(FILE_PATH, fileName);  
    }
}
 